package cl.zeke.pizzastore.negocio.services.impl;

import cl.zeke.pizzastore.finders.PerfilFinder;
import cl.zeke.pizzastore.negocio.entities.Comuna;
import cl.zeke.pizzastore.negocio.entities.Perfil;
import cl.zeke.pizzastore.negocio.services.*;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import org.hibernate.Query;
import org.hibernate.Session;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Scope;
import org.springframework.context.annotation.ScopedProxyMode;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

@Service
@Scope(proxyMode = ScopedProxyMode.INTERFACES)
public class ComunesServiceImpl implements ComunesService {

    @PersistenceContext
    private EntityManager em;

    @Autowired
    private JdbcTemplate jdbcTemplate;

    @Autowired
    private PerfilFinder perfilFinder;

    @Transactional(readOnly = true)
    @Override
    public List<Perfil> traerTodosPerfiles() {
        return perfilFinder.traerTodos();
    }

    @Transactional(readOnly = true)
    @Override
    public List<Comuna> callProcedimientoPorJPA() {
        Session session = (Session) em.getDelegate();
        Query query = session.createSQLQuery(
                "CALL procedimiento(:idRegion)")
                .addEntity(Comuna.class)
                .setParameter("idRegion", "13");

        return query.list();
    }

    @Override
    public List<Comuna> callProcedimientoPorJdbcTemplate() {
        List<Map<String, Object>> resultSet = jdbcTemplate.queryForList("CALL procedimiento(?)", 13);
        ArrayList<Comuna> comunas = new ArrayList<>();
        for (Map<String, Object> fila : resultSet) {
            Comuna comuna = new Comuna();
            comuna.setIdComuna((Integer) fila.get("ID_COMUNA"));
            comuna.setNombre((String) fila.get("NOMBRE"));
            comunas.add(comuna);
        }
        return comunas;
    }

}
